/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cerrno>
#include <net/if.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/time.h>
#include <cJSON.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/epoll.h>

#include "local_net_communication.h"
#include "local_net_utils.h"
#include "local_net_udp.h"
#include "local_net_def.h"

#include "callBackApp.h"

#ifdef L2_DEVICE
#ifdef L1_DEVICE
#include "local_net_message.h"
#endif
#include <pthread.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#endif

static int8_t msgRecv(const char *msg)
{
    char licensePlate[32] = {0};
    int ret;
    if (!msg) {
        return -1;
    }

    int8_t openFlag = 0;
    cJSON *unicastJson = cJSON_Parse(msg);
    if (!unicastJson) {
        return -1;
    }
    LOG_I("App recv msg: [%s]", msg);
    cJSON *params = cJSON_GetObjectItem(unicastJson, "params");
    if (!params) {
        LOG_E("params is null!");
        cJSON_Delete(unicastJson);
        return -1;
    }
    SAMPLE_INFO("runt that ");
    cJSON *boolOpenJson = cJSON_GetObjectItem(params, "detectResult");
    if (boolOpenJson) {
        if (!strcmp("waiting", boolOpenJson->valuestring)) {
            SAMPLE_INFO("runt that ");
            RunAICamera();
            ret = http();
            getValue(licensePlate);
            SAMPLE_INFO("licensePlate->%s", licensePlate);
            test_send_car_data(licensePlate);
            LOG_I("latch open!");
        } else {
            LOG_I("latch close!");
        }
    }

    cJSON_Delete(unicastJson);
}

// 注册信息接收回调函数
void CallBackAppInit(void)
{
    LocalNetMsgRecvCbReg(msgRecv);
}
